package cc.rengu.igas.cops.core.service.trans.payment;


import cc.rengu.igas.bomp.facade.result.Result;
import cc.rengu.igas.channel.wechat.facade.response.WechatUnifiedOrderResponse;
import cc.rengu.igas.cops.common.enums.RespCodeEnum;
import cc.rengu.igas.cops.core.service.base.PayService;
import cc.rengu.igas.cops.facade.request.WechatCreateOrderRequest;
import cc.rengu.igas.cops.facade.response.WechatCreateOrderResponse;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.base.ChannelBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.TransCustomImpl;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.*;
import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * 微信公众号支付
 * Created by LS on 2020/8/14.
 */
public class CopsWechatCreateOrderService extends PayService implements TransCustomImpl {

    @Override
    protected Object bizBeforeCust() throws Exception {
        WechatCreateOrderRequest wechatCreateOrderRequest = new WechatCreateOrderRequest();
        ConvertUtil.convertOutput(wechatCreateOrderRequest);
        /*处理上送openid*/
        if (!StringUtil.isEmptyOrNull(wechatCreateOrderRequest.getOpenId())) {
            byte[] bytes = Base64.decodeBase64(wechatCreateOrderRequest.getOpenId().getBytes(StandardCharsets.UTF_8));
            wechatCreateOrderRequest.setOpenId(new String(bytes));
        }
        return wechatCreateOrderRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        /*参数初始化*/
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /*系统流水号*/
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        rglog.debug("微信扫码下单开始，系统流水号<{}>", sysSeqNum);
        /*请求报文*/
        WechatCreateOrderRequest wechatCreateOrderRequest = (WechatCreateOrderRequest) request;
        /*机构号*/
        String instId = wechatCreateOrderRequest.getHeader().getInstId();
        /*原系统标识*/
        String srcSysId = wechatCreateOrderRequest.getHeader().getSrcSysId();
        /*authCode*/
        String authCode = wechatCreateOrderRequest.getCode();
        /*openid*/
        String openId = wechatCreateOrderRequest.getOpenId();
        /*商户号*/
        String mchntNo = wechatCreateOrderRequest.getMchntNo();
        /*交易码*/
        String txnNum = wechatCreateOrderRequest.getHeader().getTxnNum();
        /*用户订单号*/
        String userOrderId = wechatCreateOrderRequest.getUserOrderId();
        /*二维码类型*/
        String qrType = wechatCreateOrderRequest.getQrType();
        /*设置userId*/
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.USER_ID, wechatCreateOrderRequest.getOpenId());
        /*购买卡卷交易标识*/
        String isBuyCouponTrans = AppParamConstant.NO;

        //参数合法性校验
        if (StringUtil.isEmptyOrNull(userOrderId) || StringUtil.isEmptyOrNull(mchntNo) || StringUtil.isEmptyOrNull(qrType) ||
                (StringUtil.isEmptyOrNull(authCode) && StringUtil.isEmptyOrNull(openId))) {
            rglog.error("用户订单号:<{}>,商户号:<{}>,二维码类型:<{}>或openId:<{}>和授权码:<{}>上传参数存在空值！", userOrderId, mchntNo, qrType, openId, authCode);
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        //判断是否有上送卡卷,若有上送，则将优惠卷放到交易缓存中
        if (wechatCreateOrderRequest.getCouponInfo() != null && wechatCreateOrderRequest.getCouponInfo().getDiscountId() != null) {
            GlobalTransUtil.setCacheValue(TransCacheConstant.COUPON_INFO, wechatCreateOrderRequest.getCouponInfo());
        }

        //获取用户订单信息及支付订单信息
        OrderService orderService = new OrderServiceImpl();
        OrderInfo orderInfo = orderService.selectOrderInfoByUserOrderId(instId, userOrderId);
        if (null == orderInfo) {
            rglog.error("扫码动态码查无订单.订单号<{}>,渠道<{}>", wechatCreateOrderRequest.getUserOrderId(), srcSysId);
            throw new BizException(RespCodeEnum.ORDER_NOEXIT.getRespCode(), RespCodeEnum.ORDER_NOEXIT.getRespDesc());
        }
        UserOrderInfo userOrderInfo = orderInfo.getUserOrderInfo();
        List<MchntOrderInfo> mchntOrderInfoList = orderInfo.getMchntOrderInfoList();
        //用户订单userId及支付备注信息赋值
        userOrderInfo.setUserId(openId);
        userOrderInfo.setOrderDesc(wechatCreateOrderRequest.getOrderDesc());
        //订单校验金额校验及赋值
        if (StringUtil.isEmptyOrNull(userOrderInfo.getOrderAmt()) || AmountUtil.compare(userOrderInfo.getOrderAmt(), "0") == 0) {
            /*下单未输入金额，不支持合并订单支付*/
            if (mchntOrderInfoList.size() > 1) {
                rglog.error("未输入金额动态码订单不支持合并订单支付");
                throw new BizException(RespCodeEnum.ORDER_NOT_ALLOW_PAY.getRespCode(), RespCodeEnum.ORDER_NOT_ALLOW_PAY.getRespDesc());
            }
            /*单笔订单动态码扫支付，用户手输金额，应用上送金额赋值商户订单表和用户订单表*/
            userOrderInfo.setOrderAmt(wechatCreateOrderRequest.getOrderAmt());
            /*动态码暂时更新用户实际值金额、需要支付金额为订单金额，营销金额为0*/
            userOrderInfo.setNeedPayAmt(wechatCreateOrderRequest.getOrderAmt());
            userOrderInfo.setRealPayAmt(wechatCreateOrderRequest.getOrderAmt());
            userOrderInfo.setRealDiscountAmt("0.00");
            mchntOrderInfoList.get(0).setOrderAmt(wechatCreateOrderRequest.getOrderAmt());
            mchntOrderInfoList.get(0).setRealSettleAmt(wechatCreateOrderRequest.getOrderAmt());
        }

        //购买卡券不支持使用优惠券
        if ("00".equals(mchntOrderInfoList.get(0).getBizSceneType()) || "02".equals(mchntOrderInfoList.get(0).getBizSceneType())) {
            isBuyCouponTrans = AppParamConstant.YES;
            GlobalTransUtil.setCacheValue(TransCacheConstant.BUY_COUPON_TRANS_FLAG, AppParamConstant.YES);
            if (wechatCreateOrderRequest.getCouponInfo() != null && wechatCreateOrderRequest.getCouponInfo().getDiscountId() != null) {
                rglog.error("购买卡券交易不支持使用卡券");
                throw new BizException(RespCodeEnum.ORDER_NOT_ALLOW_PAY.getRespCode(), RespCodeEnum.ORDER_NOT_ALLOW_PAY.getRespDesc());
            }
        }
        //判断是否有上送卡卷,若有上送，则将优惠卷放到交易缓存中
        if (wechatCreateOrderRequest.getCouponInfo() != null && wechatCreateOrderRequest.getCouponInfo().getDiscountId() != null) {
            GlobalTransUtil.setCacheValue(TransCacheConstant.COUPON_INFO, wechatCreateOrderRequest.getCouponInfo());
        }
        //更新商户订单表校验商户限额,校验商户权限
        String wechatMchntNo = null;
        MchntService mchntService = new MchntServiceImpl();
        for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
            /*获取商户基本信息表*/
            MchntInfo mchntInfo = mchntService.getMchntInfo(instId, mchntOrderInfo.getMchntNo());
            /*判断商户是否是独立清算的门店商户*/
            if ("11".equals(mchntInfo.getMchntType()) && AppParamConstant.NO.equals(mchntInfo.getIndependentDataFlag())) {
                rglog.debug("非独立维护资料的门店商户商户订单表记录其连锁商户号");
                mchntOrderInfo.setChainMchntNo(mchntInfo.getChainMchntNo());
                mchntInfo = mchntService.getMchntInfo(instId, mchntInfo.getChainMchntNo());
            }
            /* 判断商户是否支持微信支付 */
            if (StringUtil.isEmptyOrNull(mchntInfo.getWechatMchntNo())) {
                rglog.error("商户:<{}>未开通微信业务,拒绝交易！", mchntInfo.getMchntNo());
                throw new BizException(RespCodeEnum.MCHNT_NO_PERMISSION.getRespCode(), RespCodeEnum.MCHNT_NO_PERMISSION.getRespDesc());
            }
            if (StringUtil.isEmptyOrNull(wechatMchntNo)) {
                wechatMchntNo = mchntInfo.getWechatMchntNo();
            } else if (!wechatMchntNo.equals(mchntInfo.getWechatMchntNo())) {
                rglog.info("多商户合并订单支付必须同属于一个微信子商户,不允许某个商户未到微信商户进件!");
                throw new BizException(RespCodeEnum.MCHNT_NO_PERMISSION.getRespCode(), RespCodeEnum.MCHNT_NO_PERMISSION.getRespDesc());
            }
            /* 商户交易权限检查 */
            boolean checkResult = mchntService.checkMchntAuth(instId, mchntOrderInfo.getMchntNo(), null, txnNum, wechatCreateOrderRequest.getHeader().getBizType(), AcctTypeEnum.ALL.getAcctType());
            if (!checkResult) {
                rglog.error("商户<{}>无此交易权限!", mchntOrderInfo.getMchntNo());
                throw new BizException(RespCodeEnum.NOT_SURP_TRANS_TYPE_ERROR.getRespCode(), RespCodeEnum.NOT_SURP_TRANS_TYPE_ERROR.getRespDesc());
            }
            /* 商户限额校验 */
            int limitFlag = mchntService.checkMchntTransLimit(instId, mchntOrderInfo.getRealSettleAmt(), LimitAcctTypeEnum.ALL, mchntOrderInfo.getMchntNo(), null, txnNum);
            if (limitFlag == 2 || limitFlag == 3) {
                rglog.error("商户金额超限");
                throw new BizException(RespCodeEnum.MCHNT_AMT_OVER.getRespCode(), RespCodeEnum.MCHNT_AMT_OVER.getRespDesc());
            } else if (limitFlag == 1) {
                rglog.debug("商户贷记卡超限，交易上送不支持贷记卡标识");
                xmlTreeUtil.setXmlTreeStringValue("limitPay", "no_credit");
            }
            if (AppParamConstant.NO.equals(isBuyCouponTrans)) {
                /*非购买卡卷，包括静态码和动态码处理*/
                mchntOrderInfo.setBizProdCode(txnInfo.getSrcTxnAuthCfg().getBizProdCode());
                mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                mchntOrderInfo.setSysSeqNum(sysSeqNum);
                mchntOrderInfo.setTxnNum(txnNum);
                mchntOrderInfo.setBizType(wechatCreateOrderRequest.getHeader().getBizType());
                /*实时清算判断*/
                if (wechatCreateOrderRequest.getCouponInfo() != null && wechatCreateOrderRequest.getCouponInfo().getDiscountId() != null) {
                    rglog.debug("上送优惠卡卷支付商户<{}>不允许D0", mchntOrderInfo.getMchntNo());
                    /*上送优惠卡卷支付，不能D0支付*/
                    mchntOrderInfo.setRealSettleFlag(AppParamConstant.NO);
                } else {
                    /*获取交易D0清算标识，有待处理，需要处理商户的费率信息
                     * 手续费收取方式暂不知到*/
                    /*如果是担保支付也不能D0清算,在getRealSettleFlag中处理*/
                    String realSettleFlag = mchntService.getRealSettleFlag(mchntInfo.getMchntNo(), txnInfo.getSrcTxnAuthCfg().getBizProdCode(), mchntOrderInfo.getBizSceneType(), mchntOrderInfo.getRealSettleAmt());
                    mchntOrderInfo.setRealSettleFlag(realSettleFlag);
                    /*赋值清算方式*/
                    if (AppParamConstant.YES.equals(mchntOrderInfo.getRealSettleFlag())) {
                        rglog.debug("商户D0打款<{}>", mchntOrderInfo.getMchntNo());
                        mchntOrderInfo.setRealSettleType("99");
                    }
                }
            } else {
                /*购买卡券支付*/
                mchntOrderInfo.setBizProdCode(txnInfo.getSrcTxnAuthCfg().getBizProdCode());
                mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                mchntOrderInfo.setSysSeqNum(sysSeqNum);
                mchntOrderInfo.setTxnNum(txnNum);
                mchntOrderInfo.setBizType(wechatCreateOrderRequest.getHeader().getBizType());
                mchntOrderInfo.setRealSettleFlag(AppParamConstant.NO);
            }
        }
        if (StringUtil.isEmptyOrNull(wechatMchntNo)) {
            rglog.error("扫静态码支付时，该商户的微信商户信息不存在或微信户号不存在，更新用户订单和商户订单失败");
            updateUserAndMchntOrderInf(userOrderInfo, mchntOrderInfoList, orderService);
            throw new BizException(RespCodeEnum.MCHNT_NO_PERMISSION.getRespCode(), RespCodeEnum.MCHNT_NO_PERMISSION.getRespDesc());
        }

        //先更新订单信息
        if (orderService.updateOrderInfo(userOrderInfo, mchntOrderInfoList, null)) {
            rglog.error("更新订单信息失败!");
            if ("S".equals(qrType)) {
                rglog.info("扫静态码的交易更新用户订单和商户订单为失败...");
                updateUserAndMchntOrderInf(userOrderInfo, mchntOrderInfoList, orderService);
            }
            throw new BizException(RespCodeEnum.UPDATE_ORDER_STATUS_ERROR.getRespCode(), RespCodeEnum.UPDATE_ORDER_STATUS_ERROR.getRespDesc());
        }

        //动态码判断是否为重复支付
        if ("D".equals(qrType)) {
            //非支付交易不需要设置该标识
            String redisKey = userOrderInfo.getInstId() + userOrderInfo.getMsgSrcId() + userOrderInfo.getUserOrderId();
            rglog.debug("校验订单当前是否允许支付的redisKey值:<{}>", redisKey);
            String exitRedisKey = RedisUtil.getAndSet(redisKey, AppParamConstant.YES);
            rglog.debug("当前设置RedisKey后返回的值:<{}>,用户订单当前交易状态:<{}>", exitRedisKey, userOrderInfo.getTransStatus());
            if (!StringUtil.isEmptyOrNull(exitRedisKey) && AppParamConstant.YES.equals(exitRedisKey)
                    && !TransStatusEnum.SYSTEM_REJECT.getStatus().equals(userOrderInfo.getTransStatus())) {
                rglog.info("当前订单:<{}>非交易处理失败:<{}>的订单，认定当前正处于支付中的状态,稍后获取结果", userOrderInfo.getUserOrderId(), userOrderInfo.getTransStatus());
                throw new BizException(RespCodeEnum.TRANS_IN_PROGRESS.getRespCode(), RespCodeEnum.TRANS_IN_PROGRESS.getRespDesc());
            }
            //设置当前redisKey的有效时间,时间到期后redis自动删除当前key
            RedisUtil.onceExpire(redisKey, 3);
            //动态码判断是否为同一人再次支付,若是则先关闭之前的订单
            String rePayKey = instId + userOrderInfo.getUserOrderId() + wechatCreateOrderRequest.getOpenId();
            String repayUserId = RedisUtil.onceGet(rePayKey);
            if (!StringUtil.isEmptyOrNull(repayUserId) && !BizStatusEnum.INIT.getStatus().equals(userOrderInfo.getBizStatus())) {
                //重复支付，对之前的微信订单进行关单操作
                rglog.debug("同一订单目前正在同时支付，先关闭最先开始支付的订单...");
                GlobalTransUtil.setCacheValue(TransCacheConstant.SCAN_CODE_REPAY_FLAG, AppParamConstant.YES);
            }
            RedisUtil.onceSet(rePayKey, wechatCreateOrderRequest.getOpenId(), 180);
        }

        //获取微信通道：UPWX-银联微信，NUWX-网联微信，WXZF-直连微信
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(instId, "SYS_PARAM_CHANNEL", "WECHAT_PAY_CHANNEL_ID");
        String channelType = null == sysParam ? ChannelEnum.UPWX.getChannelType() : sysParam.getParamValue().trim();
        rglog.debug("打印下单支付通道<{}>", channelType);

        //调用通道接口
        if (null == txnInfo.getChannelCallCfgList() || txnInfo.getChannelCallCfgList().isEmpty()) {
            rglog.error("<{}-{}>交易未配置交易通道服务调用配置信息！", txnInfo.getSrcTxnAuthCfg().getTxnNum(), txnInfo.getSrcTxnAuthCfg().getTxnName());
            throw new BizException(RespCodeEnum.CHANNEL_CONFIG_NOT_EXIST.getRespCode(), RespCodeEnum.CHANNEL_CONFIG_NOT_EXIST.getRespDesc());
        }
        List<ChannelCallCfg> channelCallCfgList = txnInfo.getChannelCallCfgList().stream().filter(item ->
                item.getCallIndex().equals(ChannelBaseService.FIRST_CHANNEL_CALL_INDEX)).collect(Collectors.toList());
        ChannelCallCfg channelCallCfg = channelCallSceneDiscern(wechatCreateOrderRequest, channelCallCfgList);
        Class channelClasz = Class.forName(channelCallCfg.getCallChannelImpl());
        ChannelBaseService channelBaseService = (ChannelBaseService) channelClasz.newInstance();
        channelBaseService.callService(txnInfo, orderInfo, channelCallCfg.getBizScene(), request);

        /* 组装响应信息*/
        BizResponse<WechatCreateOrderResponse> bizResponse = new BizResponse<>();
        WechatCreateOrderResponse wechatCreateOrderResponse = (WechatCreateOrderResponse) GlobalTransUtil.getCacheValue(TransCacheConstant.BIZ_RESPONSE);
        /* 请求微信成功，设置相应信息*/
        bizResponse.setRspSysId(AppParamConstant.IGAS);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(wechatCreateOrderResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        WechatCreateOrderResponse WechatCreateOrderResponse = (WechatCreateOrderResponse) ((BizResponse) response).getResult();
        ConvertUtil.convertInput(WechatCreateOrderResponse);
    }


    /**
     * 更新用户订单表/商户订单表 交易状态为拒绝，业务状态为失败
     *
     * @param userOrderInfo      用户订单
     * @param mchntOrderInfoList 商户订单
     * @throws Exception 异常
     */
    private void updateUserAndMchntOrderInf(UserOrderInfo userOrderInfo, List<MchntOrderInfo> mchntOrderInfoList, OrderService orderService) throws Exception {
        String currentDateTime = DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS");
        //更新用户订单表/商户订单表状态为失败
        userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
        userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
        userOrderInfo.setUpdateTime(currentDateTime);
        for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
            mchntOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
            mchntOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            mchntOrderInfo.setUpdateTime(currentDateTime);
        }
        if (!orderService.updateOrderInfo(userOrderInfo, mchntOrderInfoList, null)) {
            rglog.error("更新用户订单/商户订单信息失败");
        } else {
            rglog.debug("更新用户订单/商户订单信息成功");
        }
    }

    @Override
    public ChannelCallCfg channelCallSceneDiscern(Object request, List<ChannelCallCfg> channelCallCfgList) throws Exception {
        String repayFlag = (String) GlobalTransUtil.getCacheValue(TransCacheConstant.SCAN_CODE_REPAY_FLAG);
        //业务场景：00-正常扫码支付场景，01-重复支付场景
        String bizScene = (!StringUtil.isEmptyOrNull(repayFlag) && AppParamConstant.YES.equals(repayFlag)) ? "01" : "00";
        Optional<ChannelCallCfg> channelCallCfgOpt = channelCallCfgList.stream().filter(item ->
                item.getBizScene().equals(bizScene)).findFirst();
        return channelCallCfgOpt.orElse(null);
    }

    @Override
    public CheckResultEnum channelCallPreCheck(Object request, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        String scanCodeRepayFlag = (String) GlobalTransUtil.getCacheValue(TransCacheConstant.SCAN_CODE_REPAY_FLAG);
        String buyCouponTransFlag = (String) GlobalTransUtil.getCacheValue(TransCacheConstant.BUY_COUPON_TRANS_FLAG);
        //重复支付场景
        if (!StringUtil.isEmptyOrNull(scanCodeRepayFlag) && AppParamConstant.YES.equals(scanCodeRepayFlag)) {
            //在重新调起微信下单前，先更新订单信息订单状态
            if ((ChannelEnum.WXZF.getChannelType().equals(channelCallCfg.getCallChannelId()) || ChannelEnum.UPWX.getChannelType().equals(channelCallCfg.getCallChannelId()) ||
                    ChannelEnum.NUWX.getChannelType().equals(channelCallCfg.getCallChannelId())) && "unifiedorder".equals(channelCallCfg.getCallChannelTxn())) {
                UserOrderInfo userOrderInfo = Objects.requireNonNull(orderInfo).getUserOrderInfo();
                List<MchntOrderInfo> mchntOrderInfoList = orderInfo.getMchntOrderInfoList();
                OrderService orderService = new OrderServiceImpl();
                if (orderService.updateOrderStatus(userOrderInfo, mchntOrderInfoList, null)) {
                    rglog.error("关闭微信订单后，重新设置订单状态为初始状态失败!");
                    return CheckResultEnum.REFUSE;
                }
            }
        }
        //购买卡卷场景不再调用营销通道
        if (!StringUtil.isEmptyOrNull(buyCouponTransFlag) && AppParamConstant.YES.equals(buyCouponTransFlag)) {
            if (ChannelEnum.MOMP.getChannelType().equals(channelCallCfg.getCallChannelId())) {
                rglog.info("购买卡卷场景，不调用营销，直接继续调用下个通道!");
                return CheckResultEnum.NEXT;
            }
        }
        return CheckResultEnum.PASSED;
    }

    @Override
    public TransStatusEnum channelCallResultProc(Object request, ChannelCallCfg channelCallCfg, TransStatusEnum transStatusEnum, Object channelResponse, OrderInfo needUpdateOrderInfo) throws Exception {
        WechatCreateOrderRequest wechatCreateOrderRequest = (WechatCreateOrderRequest) request;
        //调用营销失败且客户使用卡卷时，则直接拒绝交易
        if (ChannelEnum.MOMP.getChannelType().equals(channelCallCfg.getCallChannelId()) && !TransStatusEnum.TRANS_SUCC.equals(transStatusEnum)) {
            if ("P01MO003".equals(channelCallCfg.getCallChannelTxn()) && null != wechatCreateOrderRequest.getCouponInfo() &&
                    (null != wechatCreateOrderRequest.getCouponInfo().getDiscountId() || null != wechatCreateOrderRequest.getCouponInfo().getDiscountAmt())) {
                rglog.error("用户支付时有使用卡卷，调用营销失败，则整个交易失败!");
                throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            }
        }
        if (TransStatusEnum.TRANS_SUCC.equals(transStatusEnum)) {
            if ("unifiedorder".equals(channelCallCfg.getCallChannelTxn())) {
                cc.rengu.igas.bomp.facade.result.Result<WechatUnifiedOrderResponse> callResult = (Result<WechatUnifiedOrderResponse>) channelResponse;
                if (null != callResult && null != callResult.getResult()) {
                    WechatUnifiedOrderResponse wechatUnifiedOrderResponse = callResult.getResult();
                    WechatCreateOrderResponse wechatCreateOrderResponse = (WechatCreateOrderResponse) GlobalTransUtil.getCacheValue(TransCacheConstant.BIZ_RESPONSE);
                    if (null == wechatCreateOrderResponse) {
                        wechatCreateOrderResponse = new WechatCreateOrderResponse();
                    }
                    wechatCreateOrderResponse.setPrePayId(wechatUnifiedOrderResponse.getPrepayId());
                    wechatCreateOrderResponse.setPayInfo(wechatUnifiedOrderResponse.getWechatpayInfo());
                    wechatCreateOrderResponse.setQrCode(wechatUnifiedOrderResponse.getCodeUrl());
                    GlobalTransUtil.setCacheValue(TransCacheConstant.BIZ_RESPONSE, wechatCreateOrderResponse);
                }
            }
        }
        return transStatusEnum;
    }
}
